package com.tbynet.wordpress;

import java.sql.Connection;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.aop.Aop;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;
import com.tbynet.wordpress.framework.directive.CompareDirective;
import com.tbynet.wordpress.model._MappingKit;
import com.tbynet.wordpress.service.CommentService;
import com.tbynet.wordpress.service.OptionService;
import com.tbynet.wordpress.service.PostService;
import com.tbynet.wordpress.service.TermService;
import com.tbynet.wordpress.service.TermTaxonomyService;
import com.tbynet.wordpress.service.UserService;
import com.tbynet.wordpress.service.provider.CommentServiceProvider;
import com.tbynet.wordpress.service.provider.OptionServiceProvider;
import com.tbynet.wordpress.service.provider.PostServiceProvider;
import com.tbynet.wordpress.service.provider.TermServiceProvider;
import com.tbynet.wordpress.service.provider.TermTaxonomyServiceProvider;
import com.tbynet.wordpress.service.provider.UserServiceProvider;

public class AppConfig extends JFinalConfig {
	
	private static Prop p = loadConfig();
	private WallFilter wallFilter;
	
	public static void main(String[] args) {
		UndertowServer.start(AppConfig.class);
	}

	@Override
	public void configConstant(Constants me) {
		me.setDevMode(p.getBoolean("devMode", false));
		me.setJsonFactory(MixedJsonFactory.me());
		me.setError404View("/404.html");
		me.setBaseUploadPath("wp-content/uploads");
		me.setBaseDownloadPath("/");
		me.setInjectDependency(true);
		
		Aop.addMapping(UserService.class, UserServiceProvider.class);
		Aop.addMapping(OptionService.class, OptionServiceProvider.class);
		Aop.addMapping(PostService.class, PostServiceProvider.class);
		Aop.addMapping(TermService.class, TermServiceProvider.class);
		Aop.addMapping(TermTaxonomyService.class, TermTaxonomyServiceProvider.class);
		Aop.addMapping(CommentService.class, CommentServiceProvider.class);
	}

	@Override
	public void configEngine(Engine me) {
		me.addDirective("compare", CompareDirective.class);
		
		me.addDirective("role", com.tbynet.wordpress.directive.RoleDirective.class);
		me.addDirective("permission", com.tbynet.wordpress.directive.PermissionDirective.class);
		
		// 包含模板文件的标签（Include tags）
		me.addDirective("get_header", com.tbynet.wordpress.directive.GetHeaderDirective.class);
		me.addDirective("get_sidebar", com.tbynet.wordpress.directive.GetSidebarDirective.class);
		me.addDirective("get_search_form", com.tbynet.wordpress.directive.GetSearchFormDirective.class);
		me.addDirective("comments_template", com.tbynet.wordpress.directive.CommentsTemplateDirective.class);
		me.addDirective("get_footer", com.tbynet.wordpress.directive.GetFooterDirective.class);

		// 博客信息标签（Blog info tags）
		me.addDirective("bloginfo", com.tbynet.wordpress.directive.BloginfoDirective.class);
		me.addDirective("bloginfo_rss", com.tbynet.wordpress.directive.BloginfoRssDirective.class);
		me.addDirective("get_bloginfo", com.tbynet.wordpress.directive.GetBloginfoDirective.class);
		me.addDirective("get_bloginfo_rss", com.tbynet.wordpress.directive.GetBloginfoRssDirective.class);

		// 列表及下拉列表的标签（Lists & Dropdown tags）
		me.addDirective("wp_list_authors", com.tbynet.wordpress.directive.WpListAuthorsDirective.class);
		me.addDirective("wp_list_categories", com.tbynet.wordpress.directive.WpListCategoriesDirective.class);
		me.addDirective("wp_list_pages", com.tbynet.wordpress.directive.WpListPagesDirective.class);
		me.addDirective("wp_list_bookmarks", com.tbynet.wordpress.directive.WpListBookmarksDirective.class);
		me.addDirective("wp_list_comments", com.tbynet.wordpress.directive.WpListCommentsDirective.class);
		me.addDirective("wp_get_archives", com.tbynet.wordpress.directive.WpGetArchivesDirective.class);
		me.addDirective("wp_page_menu", com.tbynet.wordpress.directive.WpPageMenuDirective.class);
		me.addDirective("wp_dropdown_pages", com.tbynet.wordpress.directive.WpDropdownPagesDirective.class);
		me.addDirective("wp_dropdown_categories", com.tbynet.wordpress.directive.WpDropdownCategoriesDirective.class);
		me.addDirective("wp_dropdown_users", com.tbynet.wordpress.directive.WpDropdownUsersDirective.class);

		// 登录/登出标签（Login/Logout tags）
		me.addDirective("is_user_logged_in", com.tbynet.wordpress.directive.IsUserLoggedInDirective.class);
		me.addDirective("wp_login_url", com.tbynet.wordpress.directive.WpLoginUrlDirective.class);
		me.addDirective("wp_logout_url", com.tbynet.wordpress.directive.WpLogoutUrlDirective.class);
		me.addDirective("wp_lostpassword_url", com.tbynet.wordpress.directive.WpLostpasswordUrlDirective.class);
		me.addDirective("wp_registration_url", com.tbynet.wordpress.directive.WpRegistrationUrlDirective.class);
		me.addDirective("wp_loginout", com.tbynet.wordpress.directive.WpLoginoutDirective.class);
		me.addDirective("wp_register", com.tbynet.wordpress.directive.WpRegisterDirective.class);
		me.addDirective("wp_signon", com.tbynet.wordpress.directive.WpSignonDirective.class);

		// 文章信息标签（Post tags）
		me.addDirective("the_ID", com.tbynet.wordpress.directive.TheIDDirective.class);
		me.addDirective("the_title", com.tbynet.wordpress.directive.TheTitleDirective.class);
		me.addDirective("the_title_rss", com.tbynet.wordpress.directive.TheTitleRssDirective.class);
		me.addDirective("the_title_attribute", com.tbynet.wordpress.directive.TheTitleAttributeDirective.class);
		me.addDirective("single_post_title", com.tbynet.wordpress.directive.SinglePostTitleDirective.class);
		me.addDirective("the_content", com.tbynet.wordpress.directive.TheContentDirective.class);
		me.addDirective("the_content_rss", com.tbynet.wordpress.directive.TheContentRssDirective.class);
		me.addDirective("the_excerpt", com.tbynet.wordpress.directive.TheExcerptDirective.class);
		me.addDirective("the_excerpt_rss", com.tbynet.wordpress.directive.TheExcerptRssDirective.class);
		me.addDirective("wp_link_pages", com.tbynet.wordpress.directive.WpLinkPagesDirective.class);
		me.addDirective("posts_nav_link", com.tbynet.wordpress.directive.PostsNavLinkDirective.class);
		me.addDirective("next_post_link", com.tbynet.wordpress.directive.NextPostLinkDirective.class);
		me.addDirective("next_posts_link", com.tbynet.wordpress.directive.NextPostsLinkDirective.class);
		me.addDirective("previous_post_link", com.tbynet.wordpress.directive.PreviousPostLinkDirective.class);
		me.addDirective("previous_posts_link", com.tbynet.wordpress.directive.PreviousPostsLinkDirective.class);
		me.addDirective("next_image_link", com.tbynet.wordpress.directive.NextImageLinkDirective.class);
		me.addDirective("previous_image_link", com.tbynet.wordpress.directive.PreviousImageLinkDirective.class);
		me.addDirective("sticky_class", com.tbynet.wordpress.directive.StickyClassDirective.class);
		me.addDirective("the_category", com.tbynet.wordpress.directive.TheCategoryDirective.class);
		me.addDirective("the_category_rss", com.tbynet.wordpress.directive.TheCategoryRssDirective.class);
		me.addDirective("the_tags", com.tbynet.wordpress.directive.TheTagsDirective.class);
		me.addDirective("the_meta", com.tbynet.wordpress.directive.TheMetaDirective.class);

		// 评论标签（Comment tags）
//		me.addDirective("wp_list_comments", com.tbynet.wordpress.directive.WpListCommentsDirective.class);
		me.addDirective("comments_number", com.tbynet.wordpress.directive.CommentsNumberDirective.class);
		me.addDirective("comments_link", com.tbynet.wordpress.directive.CommentsLinkDirective.class);
		me.addDirective("comments_rss_link", com.tbynet.wordpress.directive.CommentsRssLinkDirective.class);
		me.addDirective("comments_popup_script", com.tbynet.wordpress.directive.CommentsPopupScriptDirective.class);
		me.addDirective("comments_popup_link", com.tbynet.wordpress.directive.CommentsPopupLinkDirective.class);
		me.addDirective("comment_ID", com.tbynet.wordpress.directive.CommentIDDirective.class);
		me.addDirective("comment_id_fields", com.tbynet.wordpress.directive.CommentIdFieldsDirective.class);
		me.addDirective("comment_author", com.tbynet.wordpress.directive.CommentAuthorDirective.class);
		me.addDirective("comment_author_link", com.tbynet.wordpress.directive.CommentAuthorLinkDirective.class);
		me.addDirective("comment_author_email", com.tbynet.wordpress.directive.CommentAuthorEmailDirective.class);
		me.addDirective("comment_author_email_link", com.tbynet.wordpress.directive.CommentAuthorEmailLinkDirective.class);
		me.addDirective("comment_author_url", com.tbynet.wordpress.directive.CommentAuthorUrlDirective.class);
		me.addDirective("comment_author_url_link", com.tbynet.wordpress.directive.CommentAuthorUrlLinkDirective.class);
		me.addDirective("comment_author_IP", com.tbynet.wordpress.directive.CommentAuthorIPDirective.class);
		me.addDirective("comment_type", com.tbynet.wordpress.directive.CommentTypeDirective.class);
		me.addDirective("comment_text", com.tbynet.wordpress.directive.CommentTextDirective.class);
		me.addDirective("comment_excerpt", com.tbynet.wordpress.directive.CommentExcerptDirective.class);
		me.addDirective("comment_date", com.tbynet.wordpress.directive.CommentDateDirective.class);
		me.addDirective("comment_time", com.tbynet.wordpress.directive.CommentTimeDirective.class);
		me.addDirective("comment_form_title", com.tbynet.wordpress.directive.CommentFormTitleDirective.class);
		me.addDirective("comment_author_rss", com.tbynet.wordpress.directive.CommentAuthorRssDirective.class);
		me.addDirective("comment_text_rss", com.tbynet.wordpress.directive.CommentTextRssDirective.class);
		me.addDirective("comment_link_rss", com.tbynet.wordpress.directive.CommentLinkRssDirective.class);
		me.addDirective("permalink_comments_rss", com.tbynet.wordpress.directive.PermalinkCommentsRssDirective.class);
		me.addDirective("comment_reply_link", com.tbynet.wordpress.directive.CommentReplyLinkDirective.class);
		me.addDirective("cancel_comment_reply_link", com.tbynet.wordpress.directive.CancelCommentReplyLinkDirective.class);
		me.addDirective("previous_comments_link", com.tbynet.wordpress.directive.PreviousCommentsLinkDirective.class);
		me.addDirective("next_comments_link", com.tbynet.wordpress.directive.NextCommentsLinkDirective.class);
		me.addDirective("paginate_comments_links", com.tbynet.wordpress.directive.PaginateCommentsLinksDirective.class);

		// 时间及日期标签（Date and Time tags）
		me.addDirective("the_time", com.tbynet.wordpress.directive.TheTimeDirective.class);
		me.addDirective("the_date", com.tbynet.wordpress.directive.TheDateDirective.class);
		me.addDirective("the_date_xml", com.tbynet.wordpress.directive.TheDateXmlDirective.class);
		me.addDirective("the_modified_time", com.tbynet.wordpress.directive.TheModifiedTimeDirective.class);
		me.addDirective("the_modified_date", com.tbynet.wordpress.directive.TheModifiedDateDirective.class);
		me.addDirective("the_modified_author", com.tbynet.wordpress.directive.TheModifiedAuthorDirective.class);
		me.addDirective("single_month_title", com.tbynet.wordpress.directive.SingleMonthTitleDirective.class);
		me.addDirective("get_the_time", com.tbynet.wordpress.directive.GetTheTimeDirective.class);
		me.addDirective("get_day_link", com.tbynet.wordpress.directive.GetDayLinkDirective.class);
		me.addDirective("get_month_link", com.tbynet.wordpress.directive.GetMonthLinkDirective.class);
		me.addDirective("get_year_link", com.tbynet.wordpress.directive.GetYearLinkDirective.class);
		me.addDirective("get_calendar", com.tbynet.wordpress.directive.GetCalendarDirective.class);

		// 分类标签（Category tags）
		me.addDirective("is_category", com.tbynet.wordpress.directive.IsCategoryDirective.class);
//		me.addDirective("the_category", com.tbynet.wordpress.directive.TheCategoryDirective.class);
//		me.addDirective("the_category_rss", com.tbynet.wordpress.directive.TheCategoryRssDirective.class);
		me.addDirective("single_cat_title", com.tbynet.wordpress.directive.SingleCatTitleDirective.class);
		me.addDirective("category_description", com.tbynet.wordpress.directive.CategoryDescriptionDirective.class);
//		me.addDirective("wp_dropdown_categories", com.tbynet.wordpress.directive.WpDropdownCategoriesDirective.class);
//		me.addDirective("wp_list_categories", com.tbynet.wordpress.directive.WpListCategoriesDirective.class);
		me.addDirective("get_category_parents", com.tbynet.wordpress.directive.GetCategoryParentsDirective.class);
		me.addDirective("get_the_category", com.tbynet.wordpress.directive.GetTheCategoryDirective.class);
		me.addDirective("get_category_link", com.tbynet.wordpress.directive.GetCategoryLinkDirective.class);
		me.addDirective("in_category", com.tbynet.wordpress.directive.InCategoryDirective.class);

		// 作者信息标签（Author tags）
		me.addDirective("the_author", com.tbynet.wordpress.directive.TheAuthorDirective.class);
		me.addDirective("the_author_link", com.tbynet.wordpress.directive.TheAuthorLinkDirective.class);
		me.addDirective("the_author_posts", com.tbynet.wordpress.directive.TheAuthorPostsDirective.class);
		me.addDirective("the_author_posts_link", com.tbynet.wordpress.directive.TheAuthorPostsLinkDirective.class);
		me.addDirective("the_author_meta", com.tbynet.wordpress.directive.TheAuthorMetaDirective.class);
//		me.addDirective("wp_list_authors", com.tbynet.wordpress.directive.WpListAuthorsDirective.class);
//		me.addDirective("wp_dropdown_users", com.tbynet.wordpress.directive.WpDropdownUsersDirective.class);

		// 文章 Tag 标签（Tag tags）
		me.addDirective("is_tag", com.tbynet.wordpress.directive.IsTagDirective.class);
//		me.addDirective("the_tags", com.tbynet.wordpress.directive.TheTagsDirective.class);
		me.addDirective("tag_description", com.tbynet.wordpress.directive.TagDescriptionDirective.class);
		me.addDirective("single_tag_title", com.tbynet.wordpress.directive.SingleTagTitleDirective.class);
		me.addDirective("wp_tag_cloud", com.tbynet.wordpress.directive.WpTagCloudDirective.class);
		me.addDirective("wp_generate_tag_cloud", com.tbynet.wordpress.directive.WpGenerateTagCloudDirective.class);
		me.addDirective("get_the_tags", com.tbynet.wordpress.directive.GetTheTagsDirective.class);
		me.addDirective("get_the_tag_list", com.tbynet.wordpress.directive.GetTheTagListDirective.class);
		me.addDirective("get_tag_link", com.tbynet.wordpress.directive.GetTagLinkDirective.class);

		// 编辑链接标签（Edit Link tags）
		me.addDirective("edit_post_link", com.tbynet.wordpress.directive.EditPostLinkDirective.class);
		me.addDirective("edit_comment_link", com.tbynet.wordpress.directive.EditCommentLinkDirective.class);
		me.addDirective("edit_tag_link", com.tbynet.wordpress.directive.EditTagLinkDirective.class);
		me.addDirective("edit_bookmark_link", com.tbynet.wordpress.directive.EditBookmarkLinkDirective.class);

		// 固定链接标签（Permalink tags）
		me.addDirective("permalink_anchor", com.tbynet.wordpress.directive.PermalinkAnchorDirective.class);
		me.addDirective("get_permalink", com.tbynet.wordpress.directive.GetPermalinkDirective.class);
		me.addDirective("the_permalink", com.tbynet.wordpress.directive.ThePermalinkDirective.class);
		me.addDirective("permalink_single_rss", com.tbynet.wordpress.directive.PermalinkSingleRssDirective.class);

		// 链接管理标签（Links Manager tags）
//		me.addDirective("wp_list_bookmarks", com.tbynet.wordpress.directive.WpListBookmarksDirective.class);
		me.addDirective("get_bookmarks", com.tbynet.wordpress.directive.GetBookmarksDirective.class);
		me.addDirective("get_bookmark", com.tbynet.wordpress.directive.GetBookmarkDirective.class);
		me.addDirective("get_bookmark_field", com.tbynet.wordpress.directive.GetBookmarkFieldDirective.class);

		// 引用标签（Trackback tags）
		me.addDirective("trackback_url", com.tbynet.wordpress.directive.TrackbackUrlDirective.class);
		me.addDirective("trackback_rdf", com.tbynet.wordpress.directive.TrackbackRdfDirective.class);

		// 一般标签（General tags）
		me.addDirective("wp_title", com.tbynet.wordpress.directive.WpTitleDirective.class);
		me.addDirective("get_posts", com.tbynet.wordpress.directive.GetPostsDirective.class);
		me.addDirective("query_posts", com.tbynet.wordpress.directive.QueryPostsDirective.class);
		me.addDirective("the_search_query", com.tbynet.wordpress.directive.TheSearchQueryDirective.class);
	}

	@Override
	public void configHandler(Handlers me) {
		me.add(new DruidStatViewHandler("/druid"));
	}

	@Override
	public void configInterceptor(Interceptors me) {
		// TODO Auto-generated method stub

	}

	@Override
	public void configPlugin(Plugins me) {
		DruidPlugin druidPlugin = getDruidPlugin();
	    wallFilter = new WallFilter();              // 加强数据库安全
	    wallFilter.setDbType("mysql");
	    druidPlugin.addFilter(wallFilter);
	    druidPlugin.addFilter(new StatFilter());    // 添加 StatFilter 才会有统计数据
	    me.add(druidPlugin);
	    
	    ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
	    arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
	    _MappingKit.mapping(arp);
	    me.add(arp);
        if (p.getBoolean("devMode", false)) {
            arp.setShowSql(true);
        }
        
        me.add(new EhCachePlugin());
	}

	@Override
	public void configRoute(Routes me) {
		me.add(new com.tbynet.wordpress.admin.AdminRoutes());
		me.add(new com.tbynet.wordpress.portal.PortalRoutes());
	}

	private static Prop loadConfig() {
		try {
			// 优先加载生产环境配置文件
			return PropKit.use("config.properties");
		} catch (Exception e) {
			// 找不到生产环境配置文件，再去找开发环境配置文件
			return PropKit.use("config.dev.properties");
		}
	}
	
	private static DruidPlugin getDruidPlugin() {
		return new DruidPlugin(p.get("jdbcUrl"), p.get("user"), p.get("password").trim());
	}
}
